<template>
  <ElDialog
    v-model="dialogVisible"
    title="库存明细详情"
    width="900px"
    :close-on-click-modal="false"
    destroy-on-close
    append-to-body
  >
    <div v-if="detailData" class="detail-content">
      <!-- 基本信息 -->
      <ElCard class="info-section" shadow="never">
        <template #header>
          <div class="section-header">
            <ElIcon><Box /></ElIcon>
            <span>基本信息</span>
          </div>
        </template>

        <ElDescriptions :column="2" border size="default">
          <ElDescriptionsItem label="商品信息" :span="2">
            <div class="item-info">
              <div class="item-name">
                {{ detailData.item?.itemName || "-" }}
              </div>
              <div v-if="detailData.item?.itemCode" class="item-code">
                商品编号：{{ detailData.item.itemCode }}
              </div>
              <div v-if="detailData.item?.itemBrand" class="item-brand">
                品牌：{{ getBrandName(detailData.item.itemBrand) }}
              </div>
            </div>
          </ElDescriptionsItem>

          <ElDescriptionsItem label="规格信息" :span="2">
            <div class="sku-info">
              <div class="sku-name">
                {{ detailData.itemSku?.skuName || "-" }}
              </div>
              <div v-if="detailData.itemSku?.skuCode" class="sku-code">
                规格编号：{{ detailData.itemSku.skuCode }}
              </div>
              <div v-if="detailData.itemSku?.barcode" class="sku-barcode">
                条码：{{ detailData.itemSku.barcode }}
              </div>
            </div>
          </ElDescriptionsItem>

          <ElDescriptionsItem label="仓库">
            <span>{{ detailData.warehouseName || "-" }}</span>
          </ElDescriptionsItem>

          <ElDescriptionsItem label="库区">
            <span>{{ detailData.areaName || "-" }}</span>
          </ElDescriptionsItem>

          <ElDescriptionsItem label="总数量">
            <ElStatistic
              :value="Number(detailData.quantity || 0)"
              :precision="0"
              class="quantity-display"
            />
          </ElDescriptionsItem>

          <ElDescriptionsItem label="剩余数量">
            <ElStatistic
              :value="Number(detailData.remainQuantity || 0)"
              :precision="0"
              :class="getQuantityClass(detailData.remainQuantity)"
              class="quantity-display"
            />
          </ElDescriptionsItem>

          <ElDescriptionsItem label="批号">
            <span>{{ detailData.batchNo || "-" }}</span>
          </ElDescriptionsItem>

          <ElDescriptionsItem label="入库日期">
            <span>{{ formatDate(detailData.createTime) }}</span>
          </ElDescriptionsItem>

          <ElDescriptionsItem label="生产日期">
            <span>{{ formatDate(detailData.productionDate) }}</span>
          </ElDescriptionsItem>

          <ElDescriptionsItem label="过期日期">
            <span :class="getExpirationClass(detailData.expirationDate)">
              {{ formatDate(detailData.expirationDate) }}
            </span>
          </ElDescriptionsItem>
        </ElDescriptions>
      </ElCard>

      <!-- 价格和重量信息 -->
      <ElCard v-if="hasSkuDetails" class="info-section" shadow="never">
        <template #header>
          <div class="section-header">
            <ElIcon><PriceTag /></ElIcon>
            <span>价格重量信息</span>
          </div>
        </template>

        <ElRow :gutter="24">
          <ElCol :span="12">
            <div class="price-section">
              <h4>价格信息（元）</h4>
              <div
                class="price-item"
                v-if="detailData.itemSku?.costPrice !== undefined"
              >
                <span class="label">成本价：</span>
                <span class="value"
                  >¥{{ formatPrice(detailData.itemSku.costPrice) }}</span
                >
              </div>
              <div
                class="price-item"
                v-if="detailData.itemSku?.sellingPrice !== undefined"
              >
                <span class="label">销售价：</span>
                <span class="value"
                  >¥{{ formatPrice(detailData.itemSku.sellingPrice) }}</span
                >
              </div>
            </div>
          </ElCol>

          <ElCol :span="12">
            <div class="weight-section">
              <h4>重量信息（kg）</h4>
              <div
                class="weight-item"
                v-if="detailData.itemSku?.netWeight !== undefined"
              >
                <span class="label">净重：</span>
                <span class="value">{{ detailData.itemSku.netWeight }}</span>
              </div>
              <div
                class="weight-item"
                v-if="detailData.itemSku?.grossWeight !== undefined"
              >
                <span class="label">毛重：</span>
                <span class="value">{{ detailData.itemSku.grossWeight }}</span>
              </div>
            </div>
          </ElCol>
        </ElRow>

        <!-- 尺寸信息 -->
        <div v-if="hasDimensions" class="dimensions-section">
          <h4>尺寸信息（cm）</h4>
          <div class="dimensions-value">
            {{ getDimensionsText(detailData.itemSku) }}
          </div>
        </div>
      </ElCard>

      <!-- 状态分析 -->
      <ElCard class="info-section" shadow="never">
        <template #header>
          <div class="section-header">
            <ElIcon><TrendCharts /></ElIcon>
            <span>状态分析</span>
          </div>
        </template>

        <ElRow :gutter="24">
          <ElCol :span="8">
            <div class="status-item">
              <div class="status-label">库存状态</div>
              <ElTag
                :type="getStockStatusType(detailData.remainQuantity)"
                size="large"
              >
                {{ getStockStatusText(detailData.remainQuantity) }}
              </ElTag>
            </div>
          </ElCol>

          <ElCol :span="8">
            <div class="status-item">
              <div class="status-label">保质期状态</div>
              <ElTag
                :type="getExpirationStatusType(detailData.expirationDate)"
                size="large"
              >
                {{ getExpirationStatusText(detailData.expirationDate) }}
              </ElTag>
            </div>
          </ElCol>

          <ElCol :span="8">
            <div class="status-item">
              <div class="status-label">库存天数</div>
              <div class="status-value">
                {{ getStorageDays(detailData.createTime) }} 天
              </div>
            </div>
          </ElCol>
        </ElRow>
      </ElCard>

      <!-- 操作建议 -->
      <ElAlert
        v-if="getOperationSuggestion(detailData)"
        :title="getOperationSuggestion(detailData)"
        :type="getSuggestionType(detailData)"
        show-icon
        :closable="false"
        class="suggestion-alert"
      />
    </div>

    <template #footer>
      <div class="dialog-footer">
        <ElButton @click="dialogVisible = false" v-ripple> 关闭 </ElButton>
        <ElButton type="primary" @click="handleViewHistory" v-ripple>
          <ElIcon><Clock /></ElIcon>
          查看历史
        </ElButton>
      </div>
    </template>
  </ElDialog>
</template>

<script setup lang="ts">
import { computed } from "vue";
import { Box, PriceTag, TrendCharts, Clock } from "@element-plus/icons-vue";
import { formatDate } from "@/utils/date";

// 定义接口
interface ItemInfo {
  itemName?: string;
  itemCode?: string;
  itemBrand?: number;
}

interface SkuInfo {
  skuName?: string;
  skuCode?: string;
  barcode?: string;
  costPrice?: number;
  sellingPrice?: number;
  netWeight?: number;
  grossWeight?: number;
  length?: number;
  width?: number;
  height?: number;
}

interface InventoryDetailInfo {
  id: number;
  quantity: number;
  remainQuantity: number;
  batchNo?: string;
  productionDate?: string;
  expirationDate?: string;
  createTime?: string;
  warehouseName?: string;
  areaName?: string;
  item?: ItemInfo;
  itemSku?: SkuInfo;
}

// 定义props和emits
interface Props {
  visible?: boolean;
  detailData?: InventoryDetailInfo | null;
  brandMap?: Map<number, { brandName: string }>;
}

interface Emits {
  (e: "update:visible", value: boolean): void;
  (e: "view-history", data: InventoryDetailInfo): void;
}

const props = withDefaults(defineProps<Props>(), {
  visible: false,
  detailData: null,
  brandMap: () => new Map(),
});

const emit = defineEmits<Emits>();

// 对话框显示状态
const dialogVisible = computed({
  get: () => props.visible,
  set: (value: boolean) => {
    emit("update:visible", value);
  },
});

// 计算属性
const hasSkuDetails = computed(() => {
  const sku = props.detailData?.itemSku;
  return (
    sku &&
    (sku.costPrice !== undefined ||
      sku.sellingPrice !== undefined ||
      sku.netWeight !== undefined ||
      sku.grossWeight !== undefined ||
      sku.length !== undefined ||
      sku.width !== undefined ||
      sku.height !== undefined)
  );
});

const hasDimensions = computed(() => {
  const sku = props.detailData?.itemSku;
  return (
    sku &&
    (sku.length !== undefined ||
      sku.width !== undefined ||
      sku.height !== undefined)
  );
});

/**
 * 获取品牌名称
 */
function getBrandName(brandId: number): string {
  return props.brandMap?.get(brandId)?.brandName || "未知品牌";
}

/**
 * 格式化价格
 */
function formatPrice(price: number | string): string {
  if (price === undefined || price === null || price === "") return "0.00";
  return Number(price).toFixed(2);
}

/**
 * 获取尺寸文本
 */
function getDimensionsText(sku?: SkuInfo): string {
  if (!sku) return "-";

  const { length, width, height } = sku;

  if (length !== undefined && width !== undefined && height !== undefined) {
    return `${length} × ${width} × ${height}`;
  }

  const parts = [];
  if (length !== undefined) parts.push(`长：${length}`);
  if (width !== undefined) parts.push(`宽：${width}`);
  if (height !== undefined) parts.push(`高：${height}`);

  return parts.length > 0 ? parts.join(" ") : "-";
}

/**
 * 获取数量样式类
 */
function getQuantityClass(quantity: number): string {
  if (quantity <= 0) return "quantity-danger";
  if (quantity < 10) return "quantity-warning";
  return "quantity-success";
}

/**
 * 获取过期日期样式类
 */
function getExpirationClass(expirationDate?: string): string {
  if (!expirationDate) return "";

  const expDate = new Date(expirationDate);
  const now = new Date();
  const diffDays = Math.ceil(
    (expDate.getTime() - now.getTime()) / (1000 * 60 * 60 * 24),
  );

  if (diffDays <= 0) return "expired";
  if (diffDays <= 7) return "expiring-soon";
  if (diffDays <= 30) return "expiring-warning";
  return "";
}

/**
 * 获取库存状态类型
 */
function getStockStatusType(quantity: number): string {
  if (quantity <= 0) return "danger";
  if (quantity < 10) return "warning";
  return "success";
}

/**
 * 获取库存状态文本
 */
function getStockStatusText(quantity: number): string {
  if (quantity <= 0) return "缺货";
  if (quantity < 10) return "库存不足";
  return "库存充足";
}

/**
 * 获取保质期状态类型
 */
function getExpirationStatusType(expirationDate?: string): string {
  if (!expirationDate) return "info";

  const expDate = new Date(expirationDate);
  const now = new Date();
  const diffDays = Math.ceil(
    (expDate.getTime() - now.getTime()) / (1000 * 60 * 60 * 24),
  );

  if (diffDays <= 0) return "danger";
  if (diffDays <= 7) return "danger";
  if (diffDays <= 30) return "warning";
  return "success";
}

/**
 * 获取保质期状态文本
 */
function getExpirationStatusText(expirationDate?: string): string {
  if (!expirationDate) return "无保质期";

  const expDate = new Date(expirationDate);
  const now = new Date();
  const diffDays = Math.ceil(
    (expDate.getTime() - now.getTime()) / (1000 * 60 * 60 * 24),
  );

  if (diffDays <= 0) return "已过期";
  if (diffDays <= 7) return `${diffDays}天后过期`;
  if (diffDays <= 30) return `${diffDays}天后过期`;
  return "正常";
}

/**
 * 获取库存天数
 */
function getStorageDays(createTime?: string): number {
  if (!createTime) return 0;

  const createDate = new Date(createTime);
  const now = new Date();
  return Math.ceil(
    (now.getTime() - createDate.getTime()) / (1000 * 60 * 60 * 24),
  );
}

/**
 * 获取操作建议
 */
function getOperationSuggestion(data: InventoryDetailInfo): string {
  if (!data) return "";

  const storageDays = getStorageDays(data.createTime);
  const expirationDays = data.expirationDate
    ? Math.ceil(
        (new Date(data.expirationDate).getTime() - new Date().getTime()) /
          (1000 * 60 * 60 * 24),
      )
    : Infinity;

  if (expirationDays <= 0) {
    return "商品已过期，建议立即处理";
  }

  if (expirationDays <= 7) {
    return "商品即将过期，建议优先出库";
  }

  if (data.remainQuantity <= 0) {
    return "库存已耗尽";
  }

  if (storageDays > 90 && data.remainQuantity > 0) {
    return "库存周转较慢，建议关注销售情况";
  }

  return "";
}

/**
 * 获取建议类型
 */
function getSuggestionType(data: InventoryDetailInfo): string {
  const suggestion = getOperationSuggestion(data);
  if (suggestion.includes("过期") || suggestion.includes("耗尽"))
    return "error";
  if (suggestion.includes("即将") || suggestion.includes("周转"))
    return "warning";
  return "info";
}

/**
 * 查看历史
 */
function handleViewHistory(): void {
  if (props.detailData) {
    emit("view-history", props.detailData);
  }
}
</script>

<style lang="scss" scoped>
.detail-content {
  .info-section {
    margin-bottom: 20px;

    &:last-child {
      margin-bottom: 0;
    }

    .section-header {
      display: flex;
      align-items: center;
      gap: 8px;
      font-weight: 600;
      color: var(--el-text-color-primary);
    }
  }

  // 商品信息样式
  .item-info,
  .sku-info {
    .item-name,
    .sku-name {
      font-size: 16px;
      font-weight: 600;
      color: var(--el-text-color-primary);
      margin-bottom: 4px;
    }

    .item-code,
    .item-brand,
    .sku-code,
    .sku-barcode {
      font-size: 14px;
      color: var(--el-text-color-regular);
      margin-bottom: 2px;
    }
  }

  // 数量显示样式
  .quantity-display {
    &.quantity-success {
      :deep(.el-statistic__content) {
        color: var(--el-color-success);
      }
    }

    &.quantity-warning {
      :deep(.el-statistic__content) {
        color: var(--el-color-warning);
      }
    }

    &.quantity-danger {
      :deep(.el-statistic__content) {
        color: var(--el-color-danger);
      }
    }
  }

  // 过期日期样式
  .expired {
    color: var(--el-color-danger);
    font-weight: 600;
  }

  .expiring-soon {
    color: var(--el-color-danger);
    font-weight: 600;
  }

  .expiring-warning {
    color: var(--el-color-warning);
    font-weight: 600;
  }

  // 价格重量信息样式
  .price-section,
  .weight-section {
    h4 {
      margin: 0 0 12px 0;
      font-size: 14px;
      color: var(--el-text-color-primary);
    }

    .price-item,
    .weight-item {
      display: flex;
      justify-content: space-between;
      margin-bottom: 8px;

      .label {
        color: var(--el-text-color-regular);
      }

      .value {
        font-weight: 600;
        color: var(--el-text-color-primary);
      }
    }
  }

  .dimensions-section {
    margin-top: 16px;
    padding-top: 16px;
    border-top: 1px solid var(--el-border-color-light);

    h4 {
      margin: 0 0 8px 0;
      font-size: 14px;
      color: var(--el-text-color-primary);
    }

    .dimensions-value {
      font-weight: 600;
      color: var(--el-text-color-primary);
    }
  }

  // 状态分析样式
  .status-item {
    text-align: center;

    .status-label {
      font-size: 14px;
      color: var(--el-text-color-regular);
      margin-bottom: 8px;
    }

    .status-value {
      font-size: 18px;
      font-weight: 600;
      color: var(--el-text-color-primary);
    }
  }
}

.suggestion-alert {
  margin-top: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>
